package com.ruoyi.business.service.impl;

import java.util.List;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.GoodsMapper;
import com.ruoyi.business.domain.Goods;
import com.ruoyi.business.service.IGoodsService;
import com.ruoyi.business.service.IGoodsCategoryService;
import com.ruoyi.business.domain.GoodsCategory;
import org.springframework.util.StringUtils;

/**
 * 货品信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-20
 */
@Service
public class GoodsServiceImpl implements IGoodsService 
{
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private IGoodsCategoryService goodsCategoryService;


    /**
     * 查询货品信息
     * 
     * @param id 货品信息主键
     * @return 货品信息
     */
    @Override
    public Goods selectGoodsById(Long id)
    {
        Goods goods = goodsMapper.selectGoodsById(id);
//        Long goodsCategoryId = goods.getGoodsCategoryId();
//        GoodsCategory goodsCategory = goodsCategoryService.selectGoodsCategoryById(goodsCategoryId);
//        goods.setGoodsCategoryName(goodsCategory.getCategoryName());
        return goods;
    }

    /**
     * 查询货品信息列表
     * 
     * @param goods 货品信息
     * @return 货品信息
     */
   @DataScope(userAlias = "g")
   @Override
    public List<Goods> selectGoodsList(Goods goods)
    {
        return goodsMapper.selectGoodsList(goods);
    }

    /**
     * 新增货品信息
     * 
     * @param goods 货品信息
     * @return 结果
     */
    @Override
    public int insertGoods(Goods goods)
    {

        goods.setCreateTime(DateUtils.getNowDate());
        return goodsMapper.insertGoods(goods);
    }

    /**
     * 修改货品信息
     * 
     * @param goods 货品信息
     * @return 结果
     */
    @Override
    public int updateGoods(Goods goods)
    {
        goods.setUpdateTime(DateUtils.getNowDate());
        return goodsMapper.updateGoods(goods);
    }

    /**
     * 批量删除货品信息
     * 
     * @param ids 需要删除的货品信息主键
     * @return 结果
     */
    @Override
    public int deleteGoodsByIds(Long[] ids)
    {
        return goodsMapper.deleteGoodsByIds(ids);
    }

    /**
     * 删除货品信息信息
     * 
     * @param id 货品信息主键
     * @return 结果
     */
    @Override
    public int deleteGoodsById(Long id)
    {
        return goodsMapper.deleteGoodsById(id);
    }

    @Override
    public String importGoods(List<Goods> goodsList, Boolean isUpdateSupport, String operName)
    {
        if (goodsList == null || goodsList.isEmpty())
        {
            throw new RuntimeException("导入货品数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        for (Goods importGoods : goodsList)
        {
            try
            {
                // 处理货品类别ID，如果Excel传入的是类别名称而不是ID
                Object categoryObj = importGoods.getGoodsCategoryName();
                if (categoryObj != null)
                {
                    // 判断传入的是字符串类型的类别名称
                    if (categoryObj instanceof String)
                    {
                        String categoryName = (String) categoryObj;
                        // 通过类别名称查找类别ID，如果不存在则创建新类别
                        Long categoryId = getCategoryIdByName(categoryName);
                        importGoods.setGoodsCategoryId(categoryId);
                    }
                }
                
                // 根据品名规格查询是否存在
                Goods searchCondition = new Goods();
                searchCondition.setGoodsSpec(importGoods.getGoodsSpec());
                List<Goods> existingGoods = goodsMapper.selectGoodsList(searchCondition);
                
                if (existingGoods == null || existingGoods.isEmpty())
                {
                    // 新增
                    importGoods.setCreateBy(operName);
                    importGoods.setCreateTime(DateUtils.getNowDate());
                    goodsMapper.insertGoods(importGoods);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、货品 " + importGoods.getGoodsSpec() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    // 更新
                    Goods existing = existingGoods.get(0);
                    importGoods.setId(existing.getId());
                    importGoods.setCreateTime(existing.getCreateTime());
                    importGoods.setUpdateBy(operName);
                    importGoods.setUpdateTime(DateUtils.getNowDate());
                    goodsMapper.updateGoods(importGoods);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、货品 " + importGoods.getGoodsSpec() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、货品 " + importGoods.getGoodsSpec() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、货品 " + importGoods.getGoodsSpec() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new RuntimeException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    
    /**
     * 根据类别名称获取类别ID，如果不存在则创建新类别
     * 
     * @param categoryName 类别名称
     * @return 类别ID
     */
    private Long getCategoryIdByName(String categoryName) {
        if (!StringUtils.hasText(categoryName)) {
            return null;
        }
        
        GoodsCategory searchCategory = new GoodsCategory();
        searchCategory.setCategoryName(categoryName);
        List<GoodsCategory> categories = goodsCategoryService.selectGoodsCategoryList(searchCategory);
        
        if (categories != null && !categories.isEmpty()) {
            // 找到已有类别，直接返回ID
            return categories.get(0).getId();
        } else {
            // 不存在该类别，创建新类别
            GoodsCategory newCategory = new GoodsCategory();
            newCategory.setCategoryName(categoryName);
            // 生成类别代码，这里简单使用类别名称首字母
            String categoryCode = "C" + System.currentTimeMillis() % 10000;
            newCategory.setCategoryCode(categoryCode);
            // 设置父级ID为0（顶级类别）
            newCategory.setParentId(0L);
            // 设置排序
            newCategory.setOrderNum(100);
            
            // 插入新类别
            goodsCategoryService.insertGoodsCategory(newCategory);
            
            // 返回新创建的类别ID
            return newCategory.getId();
        }
    }
}
